package com.baizhi.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.lang.Console;
import com.baizhi.annotation.LogAnnotation;
import com.baizhi.service.CmfzAdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

@Controller
@RequestMapping("admin")
public class CmfzAdminController {
    @Autowired
    private CmfzAdminService cmfzAdminService;

    /**
     * 使用shiro登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("adminLogin")
    public String adminLogin(String username,String password,HttpSession session){
//        1.将用户输入的账号密码 封装在token中
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//        2.获取Subject
        Subject subject = SecurityUtils.getSubject();

//        3.通过Subject 的login方法 完成登录
        try {
            subject.login(token);

//            代码式授权
            if (subject.hasRole("admin")) {
                System.out.println("具有admin的角色");
                System.out.println("调用了支付宝给自己转钱的方法");
            }

            if (subject.isPermitted("banner:create")) {
                System.out.println("可以添加轮播图");
            }

            return "redirect:/main/main.jsp";

        }catch (Exception e){

            return "redirect:/login.jsp";
        }
    }

    @RequestMapping("captcha")
    public void getCaptcha(HttpSession session,HttpServletResponse response) throws IOException {
        //定义图形验证码的长和宽
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);

        //输出code 打印生成的验证码
        Console.log(captcha.getCode());

        //图片输出 响应流
        ServletOutputStream outputStream = response.getOutputStream();

        //图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(outputStream);

        //释放资源
        outputStream.flush();

        outputStream.close();
    }
}
